package cn.wit.summit.chwan.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GameLibraryTwoLevelAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/9/14.
 */

public class GameLibraryTwoLevelActivity extends BaseActivity {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private int pn = 1;
    private int pc = 20;
    private String typeId;
    private String title;

    private GameLibraryTwoLevelAdapter adapter;
    private List<GameLibraryTwoLevelAdapter.ViewBean> viewBeans = new ArrayList<>();
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_library_two_level);
        ButterKnife.bind(this);

        typeId = getIntent().getStringExtra("typeId");
        title = getIntent().getStringExtra("title");
        setBarTitleTx(title);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        initList();
    }

    @Override
    public void reGetData() {
        super.reGetData();
        viewBeans.clear();
        adapter.notifyDataSetChanged();
        pn = 1;
        getDailyNewData();
//        refreshLayout.autoRefresh();
    }

    private void initList() {
        adapter = new GameLibraryTwoLevelAdapter(this, viewBeans);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                getDailyNewData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getDailyNewData();
            }
        });

        showSkeleton();
        pn = 1;
        getDailyNewData();
    }

    private void getDailyNewData() {

        api.getGameLibraryTwoLevelV3(retrofitManager.gameLibraryTwoLevelV3Request(pn, typeId)).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
            @Override
            public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                hideSkeleton();
                updataUi(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                hideSkeleton();
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadMore(false);
                refreshLayout.finishRefresh();
                showToast(msg);
            }
        });
    }

    private void updataUi(List<GameListBaseBean> data) {

        if (data == null) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        if (pn == 1) {
            adapter.clearTempData();
            viewBeans.clear();
        }

        for (int i=0;i<data.size();i++) {
            viewBeans.add(new GameLibraryTwoLevelAdapter.ViewBean(GameLibraryTwoLevelAdapter.ViewType.TYPE_ITEM, data.get(i)));
        }

        if (data.size() <= 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
        } else {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            pn++;
        }

        adapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }
        super.onEventMainThread(downloadEvent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (viewBeans != null && viewBeans.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_game_lib_two_level_skeleton;
    }
}
